<?php
/**
 * IG_Model 数据资源
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Model.php 1059 2011-11-18 09:26:15Z mmxie $
 */
class IG_Data_Source_Model extends IG_Data_Source
{
    protected $_model;

    protected $_method = 'fetchPaginator';

    protected $_methodParams = array();

    public function getModel()
    {
        return $this->_model;
    }

    public function setModel($model)
    {
        if (is_string($model) && class_exists($model)) {
            $model = new $model();
        } else if (!($model instanceof IG_Model)){
            throw new IG_Exception("($model) 不存在");
        }
        $this->_model = $model;
    }

    public function getMethod()
    {
        return $this->_method;
    }

    public function setMethod($method)
    {
        $this->_method = $method;
        return $this;
    }

    public function getMethodParams()
    {
        return $this->_methodParams;
    }

    public function setMethodParams($array)
    {
        $this->_methodParams = $array;
        return $this;
    }

    public function getMeta()
    {
        if (is_null($this->_meta)) {
            $i = 0;
            $count = $this->_statement->columnCount();
            while ($i < $count) {
                $meta = $this->_statement->getColumnMeta($i);
                $this->_meta[] = $meta['name'];
                $i++;
            }
        }

        return $this->_meta;
    }

    public function run()
    {
        $methodParams = $this->getMethodParams();
        $params = $this->getParams();
        if ($this->getMethod() == 'fetchPaginator' || $this->getMethod() == 'fetchAll') {
            if (!empty($methodParams[0])) {
                foreach ($methodParams[0] as $key => $val) {
                    if (empty($params[$val])) unset($methodParams[0][$key]);
                    else $methodParams[0][$key] = $params[$val];
                }
            } else {
                foreach ($params as $key => $val) {
                    if (!empty($val)) $methodParams[0]["`$key`=?"] = $val;
                }
            }
            $result = call_user_func_array(
                array($this->getModel(), $this->getMethod()),
                $methodParams
            );
        } else {
            array_push($methodParams, $params);
            $result = call_user_func_array(
                array($this->getModel(), $this->getMethod()),
                $methodParams
            );
        }
        if ($result instanceof Zend_Paginator) {
            $this->setRows($result->getCurrentItems()->toArray());
            $this->setPaginator($result);
        } else {
            $this->setRows(method_exists($result, 'toArray') ? $result->toArray() : $result);
        }
    }
}